//
//  EmailExampleViewController.m
//  EmailExample
//

#import "EmailExampleViewController.h"

@implementation EmailExampleViewController

- (void)composeClick:(id)sender {
	if ([MFMailComposeViewController canSendMail]) {
		MFMailComposeViewController *mailController = [[MFMailComposeViewController alloc] init];
		mailController.mailComposeDelegate = self;
		
		NSArray *to = [[NSArray alloc]
					   initWithObjects:@"steve@apple.com", @"bill@microsoft.com", nil];
		[mailController setToRecipients:to];
		[to release];
		
		NSString *subject = @"some subject";
		[mailController setSubject:subject];
		
		NSString *body = @"An <b>important</b> email.";
		[mailController setMessageBody:body isHTML:YES];
		
		NSString *filePath = [[NSBundle mainBundle] pathForResource:@"apple" ofType:@"png"];
		NSData *fileData = [NSData dataWithContentsOfFile:filePath];
		[mailController addAttachmentData:fileData mimeType:@"image/png" fileName:@"apple"];
		
		[self presentModalViewController:mailController animated:YES];
	} else {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
														message:@"Can't send email!"
													   delegate:self
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		[alert show];
		[alert release];
	}

}

- (void)viewDidLoad {
    [super viewDidLoad];
	
	UIButton *compose = [UIButton buttonWithType:UIButtonTypeRoundedRect];
	CGRect composeFrame = CGRectMake(80,10,160,38);
	[compose setFrame:composeFrame];
	[compose setTitle:@"Compose Mail" forState:UIControlStateNormal];
	[compose addTarget:self
				action:@selector(composeClick:)
	  forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:compose];
}

- (void)mailComposeController:(MFMailComposeViewController *)controller
		  didFinishWithResult:(MFMailComposeResult)result
						error:(NSError *)error {
	switch (result) {
		case MFMailComposeResultCancelled:
			break;
			
		case MFMailComposeResultSaved:
			NSLog(@"mail was saved");
			break;
			
		case MFMailComposeResultSent:
			NSLog(@"mail was sent");
			break;
			
		case MFMailComposeResultFailed:
			NSLog(@"Error: %@", error);
			break;
	}
	[self dismissModalViewControllerAnimated:YES];
}

- (void)dealloc {
    [super dealloc];
}

@end
